package com.woniuxy.gobang84.service;

import java.sql.Connection;
import java.sql.SQLException;

import com.woniuxy.gobang84.dao.RecordDAO;
import com.woniuxy.gobang84.dao.UserDAO;
import com.woniuxy.gobang84.entity.Record;
import com.woniuxy.gobang84.exception.DAOException;
import com.woniuxy.gobang84.util.DbUtil;

/**
 * 对战记录Service类
 *
 * @author 老谭 (<a href="http://www.woniuxy.com">蜗牛学苑</a>)
 *
 */
public class RecordService {
	/**
	 * 记录对战信息
	 * 
	 * @param record
	 */
	public void add(Record record) {
		Connection conn = DbUtil.getConnection();
		try {
			conn.setAutoCommit(false);// 设置事务不要自动提交
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// 增加对战记录
		RecordDAO recordDAO = new RecordDAO();
		try {
			recordDAO.add(record);
			// 修改用户积分
			UserDAO userDAO = new UserDAO();
			if (record.getResult() == Record.BLACK_WIN) {
				userDAO.updateScore(record.getBlack(), 10);
				userDAO.updateScore(record.getWhite(), -10);
			} else if (record.getResult() == Record.WHITE_WIN) {
				userDAO.updateScore(record.getBlack(), -10);
				userDAO.updateScore(record.getWhite(), 10);
			} else {
				userDAO.updateScore(record.getBlack(), 5);
				userDAO.updateScore(record.getWhite(), 5);
			}
			try {
				conn.commit();// 事务提交
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} catch (DAOException e) {
			try {
				conn.rollback(); // 事务回滚
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
	}

}
